/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.oai.metadataRepository.harvest.marc21;

import cz.mzk.oai.metadataRepository.metadata.DateStamp;
import cz.mzk.oai.metadataRepository.repository.AlephBase;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Represents directory containing several export files
 * @author Martin Rehanek, Martin.Rehanek@gmail.com
 */
public class AlephExports {

    private static final String DATE_MASK = "\\d\\d\\d\\d\\d\\d\\d\\d";
    private static final String FILE_SUFFIX = ".m21";
    private static final char BASE_DATE_SEPARATOR = '-';
    private final File exportDir;
    private final String exportFileRegex;
    private final int baseLength;
    private final List<AlephExport> exports = new ArrayList<AlephExport>();

    public AlephExports(File exportDir, AlephBase base) {
        if (!exportDir.isDirectory()) {
            throw new IllegalArgumentException(exportDir.getAbsoluteFile() + " is not directory");
        }
        this.exportDir = exportDir;
        exportFileRegex = base.toString() + BASE_DATE_SEPARATOR + DATE_MASK + FILE_SUFFIX;
        baseLength = base.toString().length();
        loadExports();
    }

    private void loadExports() {
        File[] exportFiles = getExportFiles();
        for (File exportFile : exportFiles) {
            loadExportIfNotEmpty(exportFile);
        }

    }

    private File[] getExportFiles() {
        return exportDir.listFiles(new FilenameFilter() {

            public boolean accept(File dir, String name) {
                return name.matches(exportFileRegex);
            }
        });
    }

    private void loadExportIfNotEmpty(File exportFile) {
        if (exportFile.getTotalSpace() != 0) {
            int datePrefixLength = baseLength + 1;
            int dateSuffixLength = FILE_SUFFIX.length();
            AlephExport export = new AlephExport(exportFile, datePrefixLength, dateSuffixLength);
            exports.add(export);
        }
    }

    /**
     * Returns list of exports created between from and until
     * @param from
     * @param until
     * @return
     */
    public List<AlephExport> getSortedExports(DateStamp from, DateStamp until) {
        List<AlephExport> result = new ArrayList<AlephExport>();
        for (AlephExport export : exports) {
            if ((export.getDateStamp().compareTo(from) >= 0)
                    && (export.getDateStamp().compareTo(until) <= 0)) {
                result.add(export);
            }
        }
        Collections.sort(result);
        return result;
    }
}
